/**
 * Created by zenghailong on 2017/9/22.
 */

import axios from 'axios';
axios.defaults.withCredentials=true;
var  head='http://192.168.19.9:5001/';
const common = {
  url_constitute: {
    company:head+'analysis/company',//库存总览--下拉框--获取公司
    analysis_overview:head+'analysis/overview',

    head:'http://192.168.19.9:5001/',

    manager_view:'auth/view/',
    manager_freeze:'auth/freeze/',
    manager_active:'auth/active/',
    login:'auth/login/',
    logout:'auth/logout/',
    change_password:'auth/change_passwd/',
    reset_password:'auth/reset_passwd/',
    query_get_item_big_class:'decision/query/get_item_big_class/',//物料大类
    query_get_item_small_class:'decision/query/get_item_small_class/',//物料小类
    query_get_item:'decision/query/get_item/',//物料编号
    query_get_plan_class:'decision/query/get_plan_class/',//计划类别
    query_get_item_category:'decision/query/get_item_category/',//智能分类
    query_get_vendor_category:'decision/query/get_vendor_category/',//智能分类--供应商
    query_get_buyer:'decision/query/get_buyer/',//采购员
    query_get_sourcing:'decision/query/get_sourcing/',//sourcing
    query_get_planner:'decision/query/get_planner/',//计划员
    query_get_vendor:'decision/query/get_vendor/',//计划员

    item_overview: 'analysis/item/overview/',
    item_category: 'analysis/item/category/',
    item_detail: 'analysis/item/detail/',
    supplier_overview: 'analysis/supplier/overview/',
    supplier_category: 'analysis/supplier/category/',
    relevance_silent_query: 'analysis/relevance/silent_query/',
    relevance_stable_analysis: 'analysis/relevance/stable_analysis/',
    relevance_price_analysis: 'analysis/relevance/price_analysis/',
    relevance_purchase_analysis: 'analysis/relevance/purchase_analysis/',
    relevance_purchase_vendor: 'analysis/relevance/purchase_vendor/',
    relevance_vendor_detail: 'analysis/relevance/vendor_detail/',
    relevance_purchase_quarter: 'analysis/relevance/purchase_quarter/',

    feedback_item_query: 'feedback/item/query/',
    feedback_inventory_query: 'feedback/inventory/query/',
    feedback_fullfillment_query: 'feedback/fullfillment/query/',
    feedback_turnover_query: 'feedback/turnover/query/',
    feedback_lifetime_query: 'feedback/lifetime/query/',
    feedback_opo_query: 'feedback/opo/query/',
    feedback_lifetime_category: 'feedback/lifetime/category_back/',
    feedback_lifetime_overview: 'feedback/lifetime/overview_back/',
    /*lz*/
    forecastMpa0: "decision/demand/week/",					//需求预测图1 table日期选择
    forecastMpa1: "decision/demand/condition/",				//需求预测图2 table表格数据
    forecastMpa2: "decision/demand/predict_item_detail/",	//需求预测图3 折线图
    forecastMpa3: "decision/demand/condition_save/",		//需求预测图4 保存按钮
    proposalMap0: "decision/suggest/unsettle_order/",		//建议订单与到货图形1 table表格数据
    proposalMap1: "decision/suggest/new_order/",				//建议订单与到货图形2 table表格数据
    basisMap0: "decision/basis/condition/",					//决策依据图形1 table表格数据
    basisMap1: "decision/basis/table/",						//决策依据图形2 echarts图形和table表格数据
    register: "auth/register/",								//注册
    proposalMap2: "decision/action_analysis/delivery/"		//采购行为差异性分析 - 提货建议
  },
  select_url: [
    {
      "kucundalei": "decision/query/get_item_big_class/",		//智能决策select接口-库存大类下拉框
      "kucunxiaolei": "decision/query/get_item_small_class/",	//智能决策select接口-库存小类下拉框
      "wuliaobianhao": "decision/query/get_item/",				//智能决策select接口-物料编号下拉框
      "jihuayuan": "decision/query/get_planner/",				//智能决策select接口-计划员下拉框
      "caigouyuan": "decision/query/get_buyer/",				//智能决策select接口-采购员下拉框
      "zhinengfenlei": "decision/query/get_item_category/",	//智能决策select接口-智能分类下拉框
      "shijian": "decision/query/get_date_range/",				//智能决策select接口-下单开始时间、结束时间框
      "sourcing": "decision/query/get_sourcing/",				//智能决策select接口-sourcing下拉框
      "gongyingshang": "decision/query/get_vendor/",			//智能决策select接口-供应商名称下拉框
      "jihualeibie": "decision/query/get_plan_class/"			//智能决策select接口-计划类别下拉框
    }
  ],
  rem: function () {
    var fontRem;
    var winWidth;
    if (window.innerWidth) {
      winWidth = window.innerWidth;
    } else if ((document.body) && (document.body.clientWidth)) {
      winWidth = document.body.clientWidth;
    }
    winWidth <= 1200 ? ( fontRem = ( document.getElementsByTagName("html")[0].style.fontSize = "62.5px" )) : ( fontRem = ( document.getElementsByTagName("html")[0].style.fontSize = winWidth * (100 / 1920) + "px"));
    return fontRem;
  },
  footer: function () {
    if ($(window).height() >= $(document).height()) {
      $("footer").addClass("cur");
    } else {
      $("footer").removeClass("cur");
    }
  },
  getData: function (index, url, type, data, callback) {
    axios(
      {
        url: this.url_constitute.head + url,
        method: type,
        data: data
      }
    ).then(function (data) {
      callback(data);
    }).catch(function (err) {
      if (index >= 0) {
        if (err.response.status == 500) {
          if ($(".loadingBox").eq(index).length > 0) {
            $(".loadingBox").eq(index).hide();
            $("<div class='getDayaError'></div>").insertBefore($(".loadingBox").eq(index));
          } else if ($(".frame-loadding80").eq(index).length > 0) {
            $(".frame-loadding80").eq(index).hide();
            $("<div class='getDayaError'></div>").insertBefore($(".frame-loadding80").eq(index));
          }
        }
      }
    })
  },
  setDate: function (date) {
    return date.substr(0, 10);
  },
  setDateList: function (date) {
    for (var i = 0; i < date.length; i++) {
      date[i] = date[i].substr(0, 10);
    }
    return date;
  },
  setDateMonList: function (date) {
    for (var i = 0; i < date.length; i++) {
      date[i] = date[i].substr(0, 7);
    }
    return date;
  },

  numThousand: function (num) {
    if (num == null||num == undefined||isNaN(num)) {
      return '-'
    }else{
      var n = common.tofixeds(num).toString().split(".");
      var n1 = n[0];
      var n2 = n[1];
      var newN = "";
      var forN = 0;
      for (var i = n1.length - 1; i >= 0; i--) {
        if (forN % 3 == 0 && i != n1.length - 1) {
          newN = n1[i] + "," + newN
        } else {
          newN = n1[i] + newN
        }
        forN++;
      }
      if (typeof n2 != "undefined") {
        return newN + "." + n2;
      } else {
        return newN;
      }
    }
  },
  tofixeds: function (data, num) {
    if (num != "" || typeof num != "undefined") {
      num = 2;
    }
    if (String(data).indexOf(".") > -1) {
      return parseFloat(data).toFixed(num);
    } else {
      return data;
    }
  },
  clearShow: function (input) {
    if ($(input).val() != "") {
      $(input).prev(".ipt-clear").show();
    } else {
      $(input).prev(".ipt-clear").hide();
    }
    $(".ipt-clear").click(function () {
      common.liandong();
      $(this).next("input").val("").attr("data", "");
      $(this).hide();
    });
  },
  selectDate: function (id) {
    var newData = new Date();
    /*日历下拉框*/
    //具体参数说明
    //如果需要传入参数，第一个为json，第二个为回调函数
    //下面是format格式化显示格式类型，有如下几种：
    //yyyy为年数
    //大写M为月数
    //d为几号
    //h为小时
    //小写m为分钟
    //s为秒数
    //q为季度
    //小写e，为数字星期格式
    //大写E，为中文星期格式
    //举例：'yyyy年MM月dd日','yyyy-MM-dd','yyyy','MM','e','dd E'
    //注意：以上获取时间如果是个位数则返回个位数，比如7月，则返回7，如果需要返回07，参数可以写成这样“MM”，其它同理，由于时分秒功能还没有添加，默认获取当前时分秒
    calender(id).init({
      date: [newData.getFullYear(), newData.getMonth() + 1, newData.getDate()], //设置默认显示年月日，默认当前年月日
      format: 'yyyy-MM-dd', //设置显示格式
      button: false, //是否显示按钮
      left: 0, //追加left，默认0
      top: 0, //追加top，默认0
      onload: function () {
      } //初始化完成执行，this为当前创建的日历对象
    }, function (date) {
      //回调函数
      this.value = date;
      $(this).attr("data",date)
      common.clearShow(this);

	    localStorage.setItem($(this).attr("name"),date);
    });
  },
  selectDate1: function (id) {
    var newData = new Date();
    /*日历下拉框*/
    //具体参数说明
    //如果需要传入参数，第一个为json，第二个为回调函数
    //下面是format格式化显示格式类型，有如下几种：
    //yyyy为年数
    //大写M为月数
    //d为几号
    //h为小时
    //小写m为分钟
    //s为秒数
    //q为季度
    //小写e，为数字星期格式
    //大写E，为中文星期格式
    //举例：'yyyy年MM月dd日','yyyy-MM-dd','yyyy','MM','e','dd E'
    //注意：以上获取时间如果是个位数则返回个位数，比如7月，则返回7，如果需要返回07，参数可以写成这样“MM”，其它同理，由于时分秒功能还没有添加，默认获取当前时分秒
    calender1(id).init({
      date: [newData.getFullYear(), newData.getMonth() + 1, newData.getDate()], //设置默认显示年月日，默认当前年月日
      format: 'yyyy-MM-dd', //设置显示格式
      button: false, //是否显示按钮
      left: 0, //追加left，默认0
      top: 0, //追加top，默认0
      onload: function () {
      } //初始化完成执行，this为当前创建的日历对象
    }, function (date) {
      //回调函数
      this.value = date;
      if($(this).parent(".yx-form-ul").prev(".yx-form-label").text()=="起始月份"){
      	$(this).attr("date",date+"-01");
      }
      if($(this).parent(".yx-form-ul").prev(".yx-form-label").text()=="结束月份"){
      	$(this).attr("date",date+"-"+new Date(date.split("-")[0],date.split("-")[1],0).getDate());
      }
      common.clearShow(this);
    });
  },

  selectFunction: function () {
    for (var a = 0; a < $(".select.cur").length; a++) {
      $(".select.cur").find("input").attr("readonly", "readonly");
    }



//			if($("#kucunxiaolei").find("input[name='kucunxiaolei']").val()!="")
//			{
//				kucunxiaoleiVal = $("#kucunxiaolei").find("input[name='kucunxiaolei']").attr("data");
//				$("#wuliaobianhao").removeClass("cur").find("input").attr("readonly",false);
//			}else{
//				kucunxiaoleiVal = "";
//				$("#wuliaobianhao").addClass("cur").find("input").attr("readonly",true);
//			}

		function clearShow(input){
			if($(input).val()!=""){
				$(input).prev(".ipt-clear").show();
			}else{
				$(input).prev(".ipt-clear").hide();
			}
			$(".ipt-clear").click(function(){
				$(this).next("input").val("").attr("data","");
				$(this).next("input").attr("isData","false");
				common.liandong();
				$(this).hide();
			});
		}
		$(".select-box").on("click",".select input",function (event) {
			var $this = $(this);
			$(".select ul").slideUp();
			if ($(this).next("ul").is(":hidden"))
			{
				$(this).next("ul").slideDown();
			}
			/*下拉框数据请求*/
			if($(this).attr("isData")!="true"&&!$(this).parents(".select").is(".cur"))
			{
				if($this.attr("name")=="kucunxiaolei"){
					common.getData(-1,common.select_url[0][$(this).attr("name")],"post",{"big_class":window.kucundaleiVal,"dim":""},function(data){
						if(data.data.result.length<1){
							$this.val("");
							$this.next("ul").hide().html("");
							$this.parents(".select").addClass("cur");
							alert("当前库存大类下无库存小类");
						}else{
							$this.next("ul").show().html("");
							$this.parents(".select").removeClass("cur");
							for(var i=0;i<data.data.result.length;i++)
							{
								$this.next("ul").append("<li val='"+data.data.result[i].value+"'>"+data.data.result[i].value+" "+data.data.result[i].name+"</li>");
							}
							$this.attr("isData","true");
						}
					});
				}else if($this.attr("name")=="wuliaobianhao"){
					common.getData(-1,common.select_url[0][$(this).attr("name")],"post",{"big_class":window.kucundaleiVal,"item_small_class":kucunxiaoleiVal,"dim":""},function(data){
						$this.next("ul").show().html("");
						for(var i=0;i<data.data.result.length;i++)
						{
							$this.next("ul").append("<li val='"+data.data.result[i].value+"'>"+data.data.result[i].name+"</li>");
						}
						$this.attr("isData","true");
					});
				}else if($this.attr("name")=="jihualeibie"||$this.attr("name")=="zhinengfenlei"){
					common.getData(-1,common.select_url[0][$(this).attr("name")],"post",{"dim":""},function(data){
						$this.next("ul").show().html("");
						for(var i=0;i<data.data.result.length;i++)
						{
							$this.next("ul").append("<li val='"+data.data.result[i].value+"'>"+data.data.result[i].name+"</li>");
						}
						$this.attr("isData","true");
					});
				}else{
					common.getData(-1,common.select_url[0][$(this).attr("name")],"post",{"dim":""},function(data){
						$this.next("ul").show().html("");
						for(var i=0;i<data.data.result.length;i++)
						{
							$this.next("ul").append("<li val='"+data.data.result[i].value+"'>"+data.data.result[i].value+" "+data.data.result[i].name+"</li>");
						}
						$this.attr("isData","true");
					});
				}
			}
		  	event.stopPropagation();
		})
		$(".select-box").on("click", ".select ul li", function () {
			$(this).parent("ul").prev("input").val($(this).text()).attr("data",$(this).attr("val"));
			clearShow($(this).parent("ul").prev("input"));
			var $this = $(this)
			if($this.parent("ul").prev("input").attr("name")=="wuliaobianhao"){
				localStorage.setItem($this.parent("ul").prev("input").attr("name"),$this.parent("ul").prev("input").attr("data")+" "+$this.text());
			}else{
				localStorage.setItem($this.parent("ul").prev("input").attr("name"),$this.text());
			}

			common.liandong();
		})
		$(".select-box").on("keyup", ".select .td input", function () {
			if($(this).val()!="")
			{
				clearShow($(this));
				var $this = $(this);
				var postDatas = {
					"dim":$(this).val(),
					"big_class":"",
					"small_class":""
				}
				if($this.attr("name")=="kucunxiaolei"){
					postDatas.big_class = window.kucundaleiVal;
				}else if($this.attr("name")=="wuliaobianhao"){
					postDatas.big_class = window.kucundaleiVal;
					postDatas.small_class = window.kucunxiaoleiVal;
				}
				if($this.attr("name")=="wuliaobianhao"){
					common.getData(-1,common.select_url[0][$(this).attr("name")],"post",postDatas,function(data){
						$this.next("ul").show().html("");
						for(var i=0;i<data.data.result.length;i++)
						{
							$this.next("ul").append("<li val='"+data.data.result[i].value+"'>"+data.data.result[i].name+"</li>")
						}
					})
				}else{
					common.getData(-1,common.select_url[0][$(this).attr("name")],"post",postDatas,function(data){
						$this.next("ul").show().html("");
						for(var i=0;i<data.data.result.length;i++)
						{
							$this.next("ul").append("<li val='"+data.data.result[i].value+"'>"+data.data.result[i].value+" "+data.data.result[i].name+"</li>")
						}
					})
				}
			}
			common.liandong();
		})
		/*重置按钮*/
		$(".reset").click(function(){
			$(".select-box").find("input").val("");
			$(".select-box").find("input").attr("data","");
			$("input").prev(".ipt-clear").hide();
		})
		$(document).click(function () {
			$(".select ul").slideUp();
		})
	},
	setSelect:function(){
		for(var i=0;i<$(".select").length;i++){
//			console.log(typeof localStorage.getItem("aaa"));
//			console.log(localStorage.getItem("aaa"));
			var	inputName = $(".select").eq(i).find("input").attr("name");
			var inputData = localStorage.getItem(inputName)
			if(inputData){
				$(".select").eq(i).find("input").attr("data",inputData.split(" ")[0])
				if(inputName=="jihualeibie" || inputName=="zhinengfenlei" || inputName=="jueceriqi" || inputName=="xuqiuriqi" || inputName=="kaishiriqi" || inputName=="jieshuriqi"){
					$(".select").eq(i).find("input").val(inputData.split(" ")[0]);
				}else if(inputName=="wuliaobianhao" || inputName=="gongyingshang"){
					$(".select").eq(i).find("input").val(inputData.split(" ")[1]);
				}else{
					$(".select").eq(i).find("input").val(inputData.split(" ")[0]+" "+inputData.split(" ")[1]);
				}
				if(inputName=="kucunxiaolei"){
					$(".select").eq(i).removeClass("cur");
				}
				if(inputName=="kucundalei"){
					window.kucundaleiVal = inputData.split(" ")[0];
				}
				common.clearShow($(".select").eq(i).find("input"));
			}
		}
	},
	liandong:function() {
		window.kucundaleiVal = "";
    	window.kucunxiaoleiVal = "";
      if ($("#kucundalei").find("input[name='kucundalei']").val() != "") {
        window.kucundaleiVal = $("#kucundalei").find("input[name='kucundalei']").attr("data");
        $("#kucunxiaolei").removeClass("cur").find("input").attr("readonly", false);
      } else {
        window.kucundaleiVal = "";
        $("#kucunxiaolei").addClass("cur").find("input").attr("readonly", true).val("");
        $("#kucunxiaolei").find("ul").html("");
      }
    },
	wan:function(num){
		if(num>=100000000||num<-100000000){
      num=num/100000000;
      if(num%1===0){
        return num+"亿";
      }else{
        return num.toFixed(2)+"亿";
      }
    } else if (num > 10000 || num < -10000) {
      num = num / 10000;
      if (num % 1 === 0) {
        return num + "万";
      } else {
        return num.toFixed(2) + "万";
      }
    } else {
      if (num % 1 === 0) {
        return num
      } else {
        return num.toFixed(2);
      }
    }
  }
};

export default common
